<?php

namespace Home\Controller;

use Think\Controller;
use \Common\Lib\Sms\Sms;

abstract class HomeController extends Controller {

    protected $user_info;
    protected $setting;
    protected $http;
    protected $page_size;

    private $goods_category_cache = 'goods_categroy_cache';

    public function __construct() {

        $this->setting = C('setting');
        parent::__construct();
        $this->userAuthen();
        $this->initSetting();

        $this->assign('setting', $this->setting);
        if ($this->user_info) {
            $this->assign('user_info', $this->user_info);
        } else {
            $this->assign('user_info', []);
        }

        $this->http = $_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http';

        $goodsCategory = $this->cache_goods_categories(true);
        $this->assign('goodsCategory', $goodsCategory);

        $this->page_size = C('PAGE_SIZE') > 0 ? (int)C('PAGE_SIZE') : 10;

    }

    protected function cache_goods_categories($return = false) {
        $cache = S($this->goods_category_cache);
        if (empty($cache)) {
            $category = M('GoodsCategory')->order('sort ASC,id DESC')->select();
            foreach ($category as $item) {
                $cache[$item['id']] = $item;
            }
            S($this->goods_category_cache, $cache, 600);
        }

        if ($return === true) {
            return $cache;
        }
    }

    public function areas() {
        $data = S('Area_cache');
        if (empty($data)) {
            $area = M('Area')->order('area_parent_id ASC')->select();
            foreach ($area as $item) {
                $data[$item['area_id']] = $item;
            }
            unset($area);
            S('Area_cache', $data, ['expire' => 100]);
        }
        return $data;
    }

    public function get_city($ajax = true) {
        $pid = I('pid', 0, 'intval');
        $area = $this->areas();
        $return = [];
        if (!empty($area)) {
            foreach ($area as $item) {
                if ($item['area_parent_id'] == $pid) {
                    $return[] = $item;
                }
            }
        }
        if ($ajax === true) {
            echo json_encode($return);
            return;
        }
        return $return;
    }

    public function success($data = [], $message = '', $extras = []) {
        if (IS_AJAX) {
            if (!is_array($data)) {
                $message = $data;
                $data = [];
            }
            $return = [
                'status' => 'success',
                'data' => $data,
                'message' => $message,
                'extras' => $extras,
                'timestamp' => NOW_TIME,
            ];
            exit(json_encode($return, JSON_UNESCAPED_UNICODE));
        } else {
            $message = $message ? $message : ($_SERVER['HTTP_REFERER'] ? $_SERVER['HTTP_REFERER'] : '/');
            parent::success($data, $message);
        }
    }

    public function error($message, $code = '0000') {
        if (IS_AJAX) {
            $return = [
                'status' => 'error',
                'code' => $code,
                'message' => $message,
                'timestamp' => time(),
            ];
            exit(json_encode($return, JSON_UNESCAPED_UNICODE));
        } else {
            if ($code == '0000') {
                $code = '';
            }
            if ($message) {
                parent::error($message, $code);
            } else {
                redirect($code ? $code : ($_SERVER['HTTP_REFERER'] ? $_SERVER['HTTP_REFERER'] : '/'));
            }
        }
    }

    protected function userAuthen() {
        if (!cookie('_UserAuth'))
            redirect(U('/login'));
        $auth = cookie('_UserAuth');
        $token = cookie('_UserToken');
        list($id, $password) = explode("\t", authcode($auth));
        if (!$id || !$password) {
            redirect(U('/login'));
        }

        $user_info = M('User')->where(['id' => $id])->find();
//        if($user_info && $user_info['token'] != $token){
//            cookie('_UserAuth', null);
//            cookie('_UserToken',null);
//            $this->error('您的账户在其他地方登录，如果不是本人操作，您的密码可能已泄露。', U('Member/login'));
//            return false;
//        }
        if (!$user_info || $user_info['password'] != $password) {
            cookie('_UserAuth', null);
            cookie('_UserToken', null);
            redirect(U('/login'));
        }

        if ($user_info['status'] != 'ACTIVE') {
            return false;
        }

        cookie('_UserAuth', $auth, [
            'expire' => 24 * 3600 * 7,
        ]);

        $this->user_info = $user_info;
        return true;
    }


    protected function checkLogin($message = '') {
        if (!$this->user_info) {
            $this->error($message, U('/login'));
        }
    }

    /**
     * 完整地址
     */
    protected function full_url($url) {
        if (substr($url, 0, 4) == 'http') {
            return $url;
        } else {
            return 'http://' . $_SERVER['HTTP_HOST'] . '/' . ltrim($url, '/');
        }
    }

    //初始化配置
    protected function initSetting() {
        $this->setting['visit_js'] = htmlspecialchars_decode($this->setting['visit_js']);

    }

    //__call undefined method/action
    public function __call($method, $args) {
        send_http_status(404);
        $this->display('Public/404');
        exit;
    }

    //图片上传,
    protected function uploadImage($file, $ajax = false) {
        if (!$this->user_info) {
            $this->error('没有权限操作');
        }

        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 2097152;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = './Upload/'; // 设置附件上传根目录
        $upload->savePath = 'home/'; // 设置附件上传（子）目录
        $upload->mimes = array('image/jpeg', 'image/png', 'image/gif');

        $image = $upload->uploadOne($file);
        if ($image !== false) {
            $url = $upload->rootPath . $image['savepath'] . $image['savename'];
            if ($ajax === true) {
                return $this->success(['url' => $url], '上传成功', []);
            }
            return $url;
        } else {
            if ($ajax === true) {
                return $this->error($upload->getError());
            }
            return $upload->getError();
        }
    }

    //kindeditor编辑器图片上传,
    public function upload() {
        if (!$this->user_info) {
            echo json_encode(array('error' => 1, 'message' => '请先登录'));
            exit;
        }
        $file = $_FILES['imgFile'];

        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 2097152;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = './Upload/'; // 设置附件上传根目录
        $upload->savePath = 'home/'; // 设置附件上传（子）目录
        $upload->mimes = array('image/jpeg', 'image/png', 'image/gif');

        $image = $upload->uploadOne($file);

        $result = array();
        if (!$image) {// 上传错误提示错误信息
            $result = array(
                'error' => 1,
                'message' => '图片上传失败',
            );
        } else {// 上传成功
            $url = $upload->rootPath . $image['savepath'] . $image['savename'];
            $result = array(
                'error' => 0,
                "url" => $url,
                "title" => basename($image),
                'original' => $file['name'],
                'type' => $file['type'],
                'size' => $file['size']
            );
        }
        echo json_encode($result);
    }

    //上传图片，可以生成多张缩略图
    public function uploadPhotoWithThumb($file, $sub_dir = '', $thumbs = array()) {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 2097152;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = './Upload/'; // 设置附件上传根目录
        $upload->savePath = 'home/'; // 设置附件上传（子）目录
        $upload->mimes = array('image/jpeg', 'image/png', 'image/gif');

        $return = array();
        $img = '';
        $info = $upload->uploadOne($file);
        if ($info !== false) {
            $img = $upload->rootPath . $info['savepath'] . $info['savename'];
        } else {
            $this->error($upload->getError());
        }

        $return['url'] = $img;

        if (substr($img, 0, 2) == './') {
            $img = getcwd() . $img;
        }
        if (!empty($thumbs)) {
            $image = new \Think\Image();
            $image->open($img);
            foreach ($thumbs as $k => $v) {
                $thumb_name = $img . "_{$v[0]}x{$v[1]}." . $info['ext'];
                $image->thumb($v[0], $v[1], \Think\Image::IMAGE_THUMB_CENTER)->save($thumb_name);
                $return['thumbs'][] = $thumb_name;
            }
        }
        return $return;
    }

    protected function make_rand_name() {
        return uniqid() . date(s);
    }

    //公用方法
    public function treeCategory(array $arr, $selected = 0) {
        if (!is_array($arr) || empty($arr)) {
            return;
        }
        $Tree = new \Common\Lib\Tree($arr);
        $html = "<option data-type='\$type' value='\$id' \$selected>\$spacer \$name</option>";
        $result = $Tree->get_tree(0, $html, $selected, '&nbsp;&nbsp;&nbsp;&nbsp;');
        return $result;
    }

    //生成缩略图
    public function thumb_photo($photo, $width, $height, $del = false) {
        if (empty($photo)) {
            return false;
        }
        $image = new \Think\Image();
        if (!is_array($photo)) {
            $photo = array($photo);
        }
        $return = array();
        foreach ($photo as $img) {
//            if(substr($v, 0,4) != 'http'){
//                $img = getcwd().$v;
//            }else{
//                $img = $v;
//            }
            if (file_exists(getcwd() . $img)) {
                $image->open(getcwd() . $img);
            } else {
                continue;
            }

            $icon = dirname($img) . DIRECTORY_SEPARATOR . 'thumb_' . basename($img);
            $image->thumb($width, $height, \Think\Image::IMAGE_THUMB_CENTER)->save(getcwd() . $icon);  //保存

            if ($del === true) {
                unlink($img);
            }

            $return[] = $icon;
        }

        return $return;
    }

    /**
     * 短信
     * @param $mobile
     * @param string $message
     * @param int $expire
     * @return array
     */
    protected function send_sms($mobile, $message = '', $expire = 180) {
        if (isMobile($mobile)) {
            $cache = 'SMS_MOBILE_' . $mobile;
            if (!S($cache)) {
                $result = $this->sms($mobile, $message, $expire);
                if ($result['status'] == 'success') {
                    S($cache, $mobile, 60); //60秒可以重发，记住接收短信的手机号
                    return ['status' => 'success', 'msg' => "短信已发送至{$mobile}"];
                } else {
                    S('SMS_CODE_' . $mobile, null);
                    file_put_contents('./sms_error.txt', $result['errmsg']);
                    return ['status' => 'error', 'msg' => '短信发送失败'];
                }
            } else {
                $this->error('发送短信过于频繁，稍微再试');
            }
        }
        return ['status' => 'error', 'msg' => '手机号格式错误'];
    }

    /**
     * 发送短信
     * @param $mobile
     * @param string $message
     * @param int $expire
     * @return mixed
     */
    private function sms($mobile, $message = '', $expire = 180) {
        $code = mt_rand(100000, 999999);
        S('SMS_CODE_' . $mobile, $code, $expire);  //默认有效期180秒
        $msg = "【{$this->setting['site_name']}】验证码{$code}" . $message;
        return json_decode(Sms::send($mobile, $msg), true);
    }

}
